#!/bin/bash
echo In PreInst - $@

# NOTE: Any changes in this file have to be compatible for both DEB and RPM distros 
# as it is used in both installers. Use conditionals where necessary.

exitCode=0

GetDistroInstaller()
{
    local __resultvar=$1

    /usr/bin/dpkg --search /usr/bin/dpkg >/dev/null 2>&1
    if [ $? = 0 ]; then
        eval $__resultvar="DEB"
    else
        /usr/bin/rpm -q -f /usr/bin/rpm >/dev/null 2>&1
        if [ $? = 0 ]; then
            eval $__resultvar="RPM"
        else
            eval $__resultvar="UNKNOWN"
        fi
    fi
}

GetDistroInstaller DISTROINSTALLER
if [ $DISTROINSTALLER = "DEB" ]; then
    # Source debconf library.
    . /usr/share/debconf/confmodule
    db_version 2.0
fi

echo "Stopping service fabric service"
systemctl stop servicefabric 2>&1

echo "Disable service fabric service"
systemctl disable servicefabric 2>&1

if [ $DISTROINSTALLER = "DEB" ]; then
    db_get servicefabric/accepted-all-eula
    db_go
    if [ "$RET" != "true" ]; then
        db_get servicefabric/accepted-eula-ga
        db_go
        if [ "$RET" != "true" ]; then
            echo EULA not accepted. Exiting installation
            exitCode=2
        fi
    fi

    # Update to newer dotnet repo source
    grep -q "packages.microsoft.com" "/etc/apt/sources.list.d/dotnetdev.list"
    source_added="$?"
    key_added=`apt-key export BE1229CF`
    if [ "${source_added}" -ne "0" ] || [ "${key_added}" == "" ]; then
      echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-xenial-prod xenial main " >> /etc/apt/sources.list.d/dotnetdev.list
      curl "https://packages.microsoft.com/keys/microsoft.asc" | gpg --dearmor | sudo apt-key add -a
    fi

    # Update to newer jdk repo source
    grep -q "deb http://repos.azul.com/azure-only/zulu/apt stable main" "/etc/apt/sources.list"
    source_added="$?"
    key_added=`apt-key export 0x219BD9C9`
    if [ "${source_added}" -ne "0" ] || [ "${key_added}" == "" ]; then
        apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 0x219BD9C9
        apt-add-repository "deb http://repos.azul.com/azure-only/zulu/apt stable main"
    fi

    # Moby engine & Misc Microsoft Packages
    grep -q "https://packages.microsoft.com/ubuntu/16.04/prod xenial main" "/etc/apt/sources.list"
    source_added=$?
    if [ $source_added -ne 0 ]; then
        add-apt-repository "deb [arch=amd64] https://packages.microsoft.com/ubuntu/16.04/prod xenial main"
    fi

    sleep 0.001 # debconf causes script to return error 128 on slow machines if script exits too quickly
elif [ $DISTROINSTALLER = "RPM" ]; then
    echo "EULA autoaccepted for RPM"
fi

exit $exitCode
